//
//  YWLoginViewController.m
//  百布业务
//
//  Created by 陈炳桦 on 15/10/27.
//  Copyright © 2015年 陈炳桦. All rights reserved.
//

#import "YWLoginViewController.h"
#import "AFNetworking.h"
#import "YWNavigationController.h"
#import "YWHomeViewController.h"
#import "YWNetwork.h"
#import "MBProgressHUD.h"
#import "YWUserInfo.h"
#import <MJExtension.h>
#import "YWSampleType.h"
#import "YWGroup.h"
#import "YWArea.h"
#import "AppDelegate.h"

@interface YWLoginViewController ()

@property (nonatomic,strong)  UITextField *acountField;
@property (nonatomic,strong)  UITextField *pwdField;

// 提示符
@property (nonatomic,strong) MBProgressHUD *HUD;

@end

@implementation YWLoginViewController

#pragma mark - 懒加载
- (MBProgressHUD *)HUD{
    if (_HUD == nil) {
        _HUD = [[MBProgressHUD alloc] initWithView:self.view];
        _HUD.mode = MBProgressHUDModeText;
        _HUD.margin = 20.f;
        [self.view addSubview:_HUD];
    }
    return _HUD;
}


- (void)viewDidLoad {
    [super viewDidLoad];

    self.navigationItem.title = @"登录百布业务";
    
    // 背景颜色
    self.view.backgroundColor = BBRGBColor(234, 236, 238);
    
    // 设置UI
    [self setupUI];
    
    // 只显示用户名
    self.acountField.text = [YWUserInfo sharedUseInfo].name;

}

- (void)setupUI{
    // 账户文本框
    UITextField *acountField = [[UITextField alloc] init];
    acountField.clearButtonMode = UITextFieldViewModeWhileEditing;
    acountField.borderStyle = UITextBorderStyleRoundedRect;
    acountField.placeholder = @"用户名";
    UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"me_icon"]];
    imageView.frame = CGRectMake(10, 10, 20, 20);
    [acountField addSubview:imageView];
    // 占位UIView
    acountField.leftView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 35, 44)];
    acountField.leftViewMode = UITextFieldViewModeAlways;
    acountField.frame = CGRectMake(0, 10, BBScreenW, 44);
    
    self.acountField = acountField;
    [self.view addSubview:acountField];
    
    
    // 密码文本框
    UITextField *pwdField = [[UITextField alloc] init];
    pwdField.secureTextEntry = YES;
    pwdField.clearButtonMode = UITextFieldViewModeWhileEditing;
    pwdField.borderStyle = UITextBorderStyleRoundedRect;
    pwdField.placeholder = @"密码";
    UIImageView *imageView1 = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"1icon_input_password"]];
    imageView1.frame = CGRectMake(10, 10, 20, 20);
    [pwdField addSubview:imageView1];
    // 占位UIView
    pwdField.leftView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 35, 44)];
    pwdField.leftViewMode = UITextFieldViewModeAlways;
    pwdField.frame = CGRectMake(0, 60, BBScreenW, 44);
    self.pwdField = pwdField;
    [self.view addSubview:pwdField];

    // 登录按钮
    UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
    [button setTitle:@"登 录" forState:UIControlStateNormal];
    [button setBackgroundColor:BBRGBColor(85, 26, 175)];
    button.frame = CGRectMake(10, 115, BBScreenW - 20, 44);
    button.titleLabel.font = [UIFont systemFontOfSize:18];
    [button setTintColor:[UIColor whiteColor]];
    [button addTarget:self action:@selector(buttonClick) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:button];
}

- (void)buttonClick {
    // 收起键盘
    [self.view endEditing:YES];
    
    NSString *acountFieldText = self.acountField.text;
    NSString *pwdFieldText = self.pwdField.text;
    
    if ([acountFieldText isEqualToString:@""]) {
        self.HUD.labelText = @"请输入您的用户名";
        [self.HUD show:YES];
        [self.HUD hide:YES afterDelay:2];
        
        return;
    }
    
    if ([pwdFieldText isEqualToString:@""]) {
        self.HUD.labelText = @"请输入您的密码";
        [self.HUD show:YES];
        [self.HUD hide:YES afterDelay:2];
        
        return;
    }

    self.HUD.labelText = @"登录中...";
    [self.HUD show:YES];
    
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    parameters[@"name"] = acountFieldText;
    parameters[@"password"] = pwdFieldText;

    [YWNetwork loginWithParameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
       
        [self handleResponse:responseObject];
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"Error: %@", error);
    }];
}

- (void)handleResponse:(NSDictionary *)responseObject{
//     NSLog(@"JSON: %@", (NSString *)responseObject[@"flag"]);
    
    
    NSLog(@"Error: %@", responseObject);
    
    NSNumber *flag = (NSNumber *)responseObject[@"flag"];
    
    if([flag intValue] == 1){  // 登录成功
        [self.HUD hide:YES];

        // 保存用户相关信息
        YWUserInfo *useInfo = [YWUserInfo sharedUseInfo];
        useInfo.name = responseObject[@"admin"][@"name"];
        useInfo.password = responseObject[@"admin"][@"password"];
        useInfo.workId = responseObject[@"admin"][@"id"];
        useInfo.accessToken = responseObject[@"accessToken"];
        useInfo.lastLoginTime = [NSDate date];
        
        
        // 保存sampleTypeList
        NSMutableArray *sampleTypeList = [YWSampleType objectArrayWithKeyValuesArray:responseObject[@"sampleTypeList"]];
        [self saveArray:sampleTypeList withFileName:@"sampleTypeList.plist"];
        
        // 保存groupList商圈
        NSMutableArray *groupList = [YWGroup objectArrayWithKeyValuesArray:responseObject[@"groupList"]];
        [self saveArray:groupList withFileName:@"groupList.plist"];
        
        // 保存areaList地区
        NSMutableArray *areaList = [YWArea objectArrayWithKeyValuesArray:responseObject[@"areaList"]];
        [self saveArray:areaList withFileName:@"areaList.plist"];
        
        // 切换到主界面
        YWHomeViewController *homeVC = [[YWHomeViewController alloc] init];
        YWNavigationController *nav = [[YWNavigationController alloc] initWithRootViewController:homeVC];
        
        AppDelegate *delegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
        delegate.window.rootViewController = nav;
        
    }else{ // 账号异常 如账号密码不正确，账号已被禁用

        self.HUD.labelText = responseObject[@"msg"];
        [self.HUD hide:YES afterDelay:2];
    }
    
}

// 保存数组到沙盒中
- (void)saveArray:(NSArray *)array withFileName:(NSString *)fileName{
    NSString *cachePath = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)[0];
    // 拼接文件名
    NSString *filePath = [cachePath stringByAppendingPathComponent:fileName];
    // File:文件的全路径
    [NSKeyedArchiver archiveRootObject:array toFile:filePath];
}

@end
